{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.chdir(\"../\")\n",
    "\n",
    "from pathlib import Path\n",
    "\n",
    "import hydra\n",
    "import matplotlib.pyplot as plt\n",
    "import torch\n",
    "from matplotlib import colormaps as cm\n",
    "\n",
    "cmap = cm.get_cmap(\"viridis\")\n",
    "\n",
    "hydra.core.global_hydra.GlobalHydra.instance().clear()\n",
    "hydra.initialize(version_base=\"1.3\", config_path=\"../configs/\")\n",
    "cfg = hydra.compose(config_name=\"eval.yaml\")\n",
    "\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dm = hydra.utils.instantiate(cfg.data)\n",
    "dm.setup(\"test\")\n",
    "\n",
    "dl = dm.test_dataloader()\n",
    "ds = dm._data_test"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "root_dir = Path(\"logs/train/runs\")\n",
    "ckpt_path = root_dir / \"<checkpoint location>\"\n",
    "\n",
    "model = hydra.utils.instantiate(cfg.model)\n",
    "checkpoint = torch.load(ckpt_path, map_location=device)\n",
    "model.load_state_dict(checkpoint[\"state_dict\"])\n",
    "model = model.to(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in [2, 3, 4, 5]:\n",
    "    item = ds[i]\n",
    "    img = item[\"image\"]\n",
    "    plot_img = img.permute(1, 2, 0).numpy()\n",
    "    mask = item[\"target_segmentation\"]\n",
    "    person_mask = mask[1]\n",
    "\n",
    "    img = img.to(device)\n",
    "    pred_mask = torch.sigmoid(model(img.unsqueeze(0))[\"seg_logits\"][0]).detach().cpu().numpy()\n",
    "    pred_person_mask = pred_mask[1]\n",
    "\n",
    "    fig, ax = plt.subplots(1, 4, figsize=(20, 5))\n",
    "    ax[0].imshow(plot_img)\n",
    "\n",
    "    ax[1].imshow(person_mask, cmap=\"gray\")\n",
    "\n",
    "    ax[2].imshow(pred_person_mask, cmap=\"gray\", vmin=0, vmax=1)\n",
    "\n",
    "    thresholded_pred_person_mask = pred_person_mask > 0.5\n",
    "    ax[3].imshow(thresholded_pred_person_mask, cmap=\"gray\")\n",
    "\n",
    "    plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "monseg",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
